#include <my_header.h>
#include <string.h>
#define BUF_SIZE 4096

/* Usage: mkfifo 创建管道文件 */
int main(int argc, char *argv[]){  
    // 创建Socket对象：IPv4, TCP
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    // 开启端口复用
    int reuse = 1;
    setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));  

    // 设定服务器端口与IP地址
    char *port = "9080";
    char *ip = "0.0.0.0";
    struct sockaddr_in sock;
    sock.sin_family = AF_INET;			// IPv4
    sock.sin_port = htons(atoi(port));		// 端口号（转大端）
    sock.sin_addr.s_addr = inet_addr(ip);	// ip号（转大端）

    // 绑定端口和IP
    int ret = bind(socket_fd, (struct sockaddr *)&sock, sizeof(sock));
    ERROR_CHECK(ret , -1, "bind");

    // 开始监听(按照TCP的方式开始监听)
    listen(socket_fd, 10);

    // 取出一个全新的socket对象, 用新的socket对象服务于客户端
    struct sockaddr_in sock_client;
    socklen_t len = sizeof(sock_client);
    int net_fd = accept(socket_fd, (struct sockaddr *)&sock_client, &len);

    printf("server_v1 line34 : 服务器完成三次握手 :%s  \n",  inet_ntoa(sock_client.sin_addr));

    char sendbuf[BUF_SIZE] = {0};
    char recvbuf[BUF_SIZE] = {0};

    while(1){
        fd_set set;
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(net_fd, &set);

        select(net_fd + 1, &set, NULL, NULL, NULL);

        // B read pipe and print
        if(FD_ISSET(net_fd, &set)){
            bzero(recvbuf, sizeof(recvbuf));
            ssize_t read_count1 = read(net_fd, recvbuf, sizeof(recvbuf));
            if(read_count1 <= 0) break;

            printf("B recv > %s ", recvbuf);
            fflush(stdout);
        }

        // B input and send pipe
        if(FD_ISSET(STDIN_FILENO, &set)){
            bzero(sendbuf, sizeof(sendbuf));
            printf("B input > ");
            fflush(stdout);

            ssize_t read_count2 = read(STDIN_FILENO, sendbuf, sizeof(sendbuf));
            if(read_count2 <= 0) break;
            printf("%s \n", sendbuf);
            write(net_fd, sendbuf, sizeof(sendbuf));
            sendbuf[read_count2] = '\0';
        }
    }

    close(socket_fd);
    close(net_fd);
    return 0;
}

